package com.the9tcat.deliverycoming.net;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import com.the9tcat.deliverycoming.util.CommonMethod;

/**
 * Not used
 * 
 * @author jianhpin
 *
 */

public class HttpParse {

	/**
	 * use get method to fetch data
	 * @param url
	 * @return
	 * @throws IOException
	 */
	public String GET(String url) throws IOException{
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet get = new HttpGet(url);
		setHeader(get);
		HttpResponse response = httpclient.execute(get);
		int code = 0;
		code = response.getStatusLine().getStatusCode();
		if(code==200){
			return getFromZip(response);
		}else{
			throw new IOException("Host is not accessable");
		}
	}
	/**
	 * use post method to fetch data, cannot upload file
	 * @param url
	 * @param parameters
	 * @return
	 * @throws IOException
	 */
	public String POST(String url,Map<String,String> parameters) throws IOException{
		return POST(url,null,null,parameters);
	}
	/**
	 * use post method to fetch data, support file upload
	 * @param url  the URL you requested
	 * @param file  the file you want to upload
	 * @param fileFormName the file's form name
	 * @param parameters other parameters
	 * @return
	 * @throws IOException
	 */
	public String POST(String url, File file, String fileFormName,
			Map<String, String> parameters) throws IOException {
		HttpURLConnection conn = null;
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "---------------------------28318289637813";
		try {
			// Make a connect to the server
			URL _url = new URL(url);
			conn = (HttpURLConnection) _url.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("connection", "keep-alive");
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setConnectTimeout(50000);
			conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
			conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);
			// Send the body
			DataOutputStream dataOS = new DataOutputStream(conn.getOutputStream());
			if (parameters != null) {
				String tmp_param;
				for (String key : parameters.keySet()) {
					tmp_param = parameters.get(key);
					if(tmp_param!=null){
						dataOS.writeBytes(twoHyphens + boundary + end);
						dataOS.writeBytes("Content-Disposition: form-data; "
								+ "name=\"" + key + "\"" + end + end);
						dataOS.write(tmp_param.getBytes("utf-8"));
						dataOS.writeBytes(end);
					}
				}
			}
			if(file!=null&&fileFormName!=null){
				dataOS.writeBytes(twoHyphens + boundary + end);
				dataOS.writeBytes("Content-Disposition: form-data; " + "name=\""
						+ fileFormName + "\";filename=\"" + file.getName() + "\""
						+ end);
				dataOS.writeBytes("Content-Type: image/"+CommonMethod.getFileType(file)+ end);
				dataOS.writeBytes(end);
				FileInputStream fStream = new FileInputStream(file);
				int bufferSize = 1024;
				byte[] buffer = new byte[bufferSize];
				int length = -1;
				while ((length = fStream.read(buffer)) != -1) {
					dataOS.write(buffer, 0, length);
				}
				fStream.close();
				dataOS.writeBytes(end);
				
			}
			dataOS.writeBytes(twoHyphens + boundary + twoHyphens + end);
			dataOS.flush();
			dataOS.close();
			// Ensure we got the HTTP 200 response code
			int responseCode = conn.getResponseCode();
			InputStream is = conn.getInputStream();
			if (responseCode == 200) {
				return getFromZip(is);
			}else{
				throw new IOException("Host is not accessable");
			}
		} catch (IOException e) {
			throw e;
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}
	}
	/**
	 * Add some parameters in http request, then server will treat our request as browser or other clients
	 * @param hm
	 */
	private void setHeader(HttpRequest hm) {
		HttpParams httpParameters = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
		HttpConnectionParams.setSoTimeout(httpParameters, 70000);
		hm.setParams(httpParameters);
		hm.addHeader("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.9) Gecko/20100824 Firefox/3.6.9 ( .NET CLR 3.5.30729)");
		hm.addHeader("Accept","application/x-www-form-urlencode");
		hm.addHeader("Accept-Language", "en-us,en;q=0.5");
		hm.addHeader("Accept-Encoding", "gzip,deflate");
		hm.addHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
		hm.addHeader("Keep-Alive", "115");
		hm.addHeader("Connection", "keep-alive");
		hm.addHeader("Referer", "url");
	}
	/**
	 * decompress the response
	 * @param hm
	 * @return
	 * @throws IOException
	 */
	private String getFromZip(HttpResponse hm) throws IOException {
		if(hm==null){
			throw new IOException("Did not get response from server");
		}
		InputStream is = hm.getEntity().getContent();
		return getFromZip(is);
	}

	/**
	 * decompress the stream
	 * @param is
	 * @return
	 * @throws IOException
	 */
	private String getFromZip(InputStream is) throws IOException{
		InputStream gzin = new GZIPInputStream(is);
		InputStreamReader isr = new InputStreamReader(gzin, "utf-8");
		java.io.BufferedReader br = new java.io.BufferedReader(isr);
		String tempbf;
		StringBuffer sb = new StringBuffer();
		while ((tempbf = br.readLine()) != null) {
			sb.append(tempbf);
			sb.append("\r\n");
		}
		isr.close();
		gzin.close();
		return sb.toString();
	}
}
